import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:get/get.dart';
import 'package:signage/app/data/models/si_font.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:signage/widgets/custom_appbar.dart';

import '../controllers/font_manager_controller.dart';

class FontManagerView extends GetView<FontManagerController> {
  const FontManagerView({super.key});
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFF3F4F6),
        appBar: CustomAppBar(
          backgroundColor: Colors.white,
          title: controller.isSelectMode.value 
              ? AppLocalizations.of(context)!.translate('select_font')
              : AppLocalizations.of(context)!.translate('font_management'),
          showBackButton: true,
        ),
        body: Column(
          children: [
            Expanded(
              child: Obx(() => SingleChildScrollView(
                    child: Column(
                      children: [
                        Container(
                      margin: const EdgeInsets.all(16),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          // 本地字体区域
                          Text(
                            AppLocalizations.of(context)!.translate('local_fonts'),
                            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 12),
                          // 本地字体列表
                          _buildLocalFontList(),
                        ],
                      ),
                    ),
                    if (controller.networkFonts.isNotEmpty)
                      // 网络字体列表
                      _buildNetworkFontList(),
                  ],
                ),
                ),)
            ) ,
            if (!controller.isSelectMode.value)
              Container(
                width: Get.width,
                decoration: BoxDecoration(
                  color: Colors.white,
                ),
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: controller.importFonts,
                      child: Container(
                        height: 40,
                        margin:
                            const EdgeInsets.only(left: 16, right: 16, top: 16),
                        decoration: BoxDecoration(
                          color: Color(0XFFFCCF01),
                          borderRadius: BorderRadius.circular(28),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              'assets/images/Frame@2x (10).png',
                              width: 19.w,
                              height: 19.w,
                            ),
                            8.horizontalSpace,
                            Text(
                              AppLocalizations.of(context)!.translate('import_font'),
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w400,
                                letterSpacing: 0,
                                color: Color(0xFF333333),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    6.verticalSpace,
                    Text(
                      AppLocalizations.of(context)!.translate('supported_formats'),
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w400,
                        letterSpacing: 0,
                        color: Color(0xFF999999),
                      ),
                    ),
                    6.verticalSpace,
                  ],
                ),
              )
          ],
        ));
  }

  Widget _buildNetworkFontList() {
    return Container(
      margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            AppLocalizations.of(Get.context!)!.translate('available_fonts'),
            style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 12),
          Obx(() => Column(
                children: [
                  ...controller.networkFonts.map((font) => _buildFontItem(
                        font.name,
                        '',
                        showDelete: false,
                        showDownload: true,
                      )),
                ],
              )),
        ],
      ),
    );
  }

  Widget _buildLocalFontList() {
    return Obx(() => Column(
          children: [
            // 显示内置字体，每个字重作为独立字体显示
            ...controller.builtInFonts.expand((font) {
              List<Widget> items = [];
              if (font.variants != null) {
                for (var entry in font.variants!.entries) {
                  items.add(_buildFontItem(
                    '${font.name} ${SIFont.weightToString(entry.key)}',
                    AppLocalizations.of(Get.context!)!.translate('built_in'),
                    showDelete: false,
                  ));
                }
              }
              return items;
            }),
            // 显示已安装字体
            ...controller.installedFonts.map((font) => _buildFontItem(
                  font.name,
                  '',
                  showDelete: true,
                )),
          ],
        ));
  }

  Widget _buildFontItem(
    String title,
    String subtitle, {
    bool showDelete = false,
    bool showDownload = false,
  }) {
    return InkWell(
      onTap: () {
        if (controller.isSelectMode.value) {
          // 在选择模式下，点击时返回选中的字体
          final font = controller.builtInFonts.expand((font) {
            if (font.variants == null) return [];
            return font.variants!.entries.map((entry) {
              final fullName =
                  '${font.name} ${SIFont.weightToString(entry.key)}';
              if (fullName == title) return font;
            }).whereType<SIFont>();
          }).firstWhere(
            (f) => true,
            orElse: () => controller.installedFonts.firstWhere(
              (f) => f.name == title,
              orElse: () => throw Exception('Font not found: $title'),
            ),
          );
          controller.selectFont(font);
        }
      },
      child: Container(
        padding: const EdgeInsets.all(12),
        margin: const EdgeInsets.only(bottom: 8),
        decoration: BoxDecoration(
          color: const Color(0xFFF6F7F9),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Row(
          children: [
            // 添加单选框
            if (controller.isSelectMode.value) ...[
              Obx(() => Radio<String>(
                    value: title,
                    groupValue: controller.selectedFont.value?.name,
                    onChanged: (value) {
                      if (value == null) return;
                      final font = controller.builtInFonts.expand((font) {
                        if (font.variants == null) return [];
                        return font.variants!.entries.map((entry) {
                          final fullName =
                              '${font.name} ${SIFont.weightToString(entry.key)}';
                          if (fullName == value) return font;
                        }).whereType<SIFont>();
                      }).firstWhere(
                        (f) => true,
                        orElse: () => controller.installedFonts.firstWhere(
                          (f) => f.name == value,
                          orElse: () =>
                              throw Exception('Font not found: $value'),
                        ),
                      );
                      controller.selectFont(font);
                    },
                    activeColor: Color(0XFFFCCF01),
                  )),
              const SizedBox(width: 8),
            ],
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16,
                      fontFamily: title.split(' ')[0],
                      fontWeight: SIFont.getFontWeight(title),
                    ),
                  ),
                  const SizedBox(height: 4),
                ],
              ),
            ),
            if (subtitle.isNotEmpty)
            Container(
              height: 28,
              padding: EdgeInsets.only(left: 7.w, right: 7.w),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Center(
                child: Text(
                  subtitle,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w400,
                    letterSpacing: 0,
                    color: Color(0xFF333333),
                  ),
                ),
              ),
            ),

            if (showDelete)
            SizedBox(
              width: 24,
              height: 24,
              child: IconButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  controller.removeFont(title);
                },
                icon: const Icon(Icons.delete_outline, color: Color(0XFFFCCF01),
                size: 24,),
              ),
            ),
            if (showDownload)
              Obx(() => controller.downloadProgress.containsKey(title)
                  ? SizedBox(
                      width: 24,
                      height: 24,
                      child: CircularProgressIndicator(
                        value: controller.downloadProgress[title],
                        color: const Color(0XFFFCCF01),
                        strokeWidth: 2,
                      ),
                    )
                  : Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: const Color(0XFFFCCF01),
                        borderRadius: BorderRadius.circular(4),
                      ),
                      child: IconButton(
                        padding: EdgeInsets.zero,
                        onPressed: () => controller.downloadFont(title),
                        icon: const Icon(
                          Icons.download_outlined,
                          color: Colors.white,
                          size: 20,
                        ),
                      ),
                    )),
          ],
        ),
      ),
    );
  }
}

class FontListItem extends StatelessWidget {
  final SIFont font;

  const FontListItem({required this.font, Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Color(0xFFF3F4F6),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            font.name,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
            ),
          ),
          const SizedBox(height: 8),
          if (font.variants != null) ...[
            for (var weight in SIFontWeight.values)
              if (font.getVariant(weight) != null)
                Padding(
                  padding: const EdgeInsets.only(left: 16, top: 4),
                  child: Text(
                    '${SIFont.weightToString(weight)} - ${font.getVariant(weight)}',
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                    ),
                  ),
                ),
          ],
          const SizedBox(height: 4),
          Text(
            '内置字体',
            style: TextStyle(
              fontSize: 12,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }
}
